package com.umeox.mediaplayer

import android.app.Activity
import android.content.*
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import androidx.lifecycle.ViewModelProvider
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.umeox.moto.watch.themes.app.ThemeFragment
import com.umeox.moto.watch.themes.dialog.ActionOptionsDialog
import com.yc.music.model.AudioBean
import com.yc.music.service.PlayService
import com.yc.music.service.PlayService.PlayBinder
import com.yc.music.tool.BaseAppHelper
import java.util.logging.Logger

class MusicListFragment : ThemeFragment(), MusicListAdapter.ItemClickListener,
    ActionOptionsDialog.OnClickListener {

    private lateinit var moviesAdapter: MusicListAdapter
    private lateinit var refreshView: SwipeRefreshLayout
    private lateinit var musicViewModel: MusicViewModel
    private var playerControlFl: FrameLayout? = null
    private lateinit var musicPlayerControlView: MusicPlayerControlView
    private lateinit var mPlayServiceConnection: PlayServiceConnection
    var loadingView: View? = null

    val ICONS = intArrayOf(R.drawable.item_remove)
    val DESTS = intArrayOf(R.string.str_remove)

    private var mCurrentAudio: AudioBean? = null

    private lateinit var mLocalBroadcastManager: LocalBroadcastManager
    private val myLocalBroadcastReceiver = MyLocalBroadcastReceiver()

    override fun initView(rootView: View) {
        super.initView(rootView)
        startCheckService(rootView)
        val moviesRv: RecyclerView = rootView.findViewById(R.id.rv_movies)
        loadingView = rootView.findViewById(R.id.pb_load_file)
        refreshView = rootView.findViewById(R.id.srf)

        playerControlFl = rootView.findViewById(R.id.fl_player_control)
        refreshView.setOnRefreshListener {
            setupMovieBeanList()
        }

        moviesAdapter = MusicListAdapter()
        moviesRv.adapter = moviesAdapter
        moviesRv.setHasFixedSize(true)
        moviesRv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)

        moviesAdapter.itemClickListener = this

        musicViewModel = ViewModelProvider(this)[MusicViewModel::class.java]

        musicViewModel.musicLiveData.observe(this) {
            loadingView?.visibility = View.GONE

            moviesAdapter.setDataList(it)
            val musicList = BaseAppHelper.get().musicList
            Log.e("TAG", "musicList=$musicList")
            musicList.clear()
            musicList.addAll(it)
            Log.e("TAG", "musicList=$musicList")
            if (refreshView.isRefreshing) {
                refreshView.isRefreshing = false
            }
        }
        setupMovieBeanList()

        registerLocalBroadcast()
    }

    private fun registerLocalBroadcast() {
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(requireContext())
        //注册广播接收器
        val intentFilter = IntentFilter()
        intentFilter.addAction("com.umeox.intent.ACTION_REFRESH")
        mLocalBroadcastManager.registerReceiver(myLocalBroadcastReceiver, intentFilter)
    }

    override fun onResume() {
        super.onResume()
        val playService = BaseAppHelper.get().playService
        if (playService != null && (playService.isPlaying || playService.isPausing)) {

            showMusicPlayerControlView()
        }
    }

    private fun showMusicPlayerControlView() {
        playerControlFl?.apply {
            if (!::musicPlayerControlView.isInitialized) {
                musicPlayerControlView = MusicPlayerControlView(context)
                val layoutParams = FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT
                )
                addView(musicPlayerControlView, layoutParams)
            }
        }
    }


    /**
     * 检测服务
     */
    private fun startCheckService(rootView: View) {

        if (BaseAppHelper.get().playService == null) {
            startService()
            rootView.postDelayed({ bindService() }, 500)
        }
    }

    /**
     * 开启服务
     */
    private fun startService() {
        val intent = Intent(requireContext(), PlayService::class.java)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            requireContext().startForegroundService(intent)
        } else {
            requireContext().startService(intent)
        }
    }


    /**
     * 绑定服务
     * 注意对于绑定服务一定要解绑
     */
    private fun bindService() {

        val intent = Intent()

        intent.setClass(mContext, PlayService::class.java)
        mPlayServiceConnection = PlayServiceConnection()
        val bindService =
            mContext.bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE)


    }

    class PlayServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {

            BaseAppHelper.get().playService = (service as PlayBinder).service
        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }

    private fun setupMovieBeanList() {
        loadingView?.also {
            it.visibility = View.VISIBLE
        }
        musicViewModel.getMusicList()
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        if (requestCode == 200 && grantResults[0] == PERMISSION_GRANTED) {
            setupMovieBeanList()
        }
    }

    override fun onItemClicked(movie: AudioBean) {
        val intent = Intent(requireContext(), MusicActivity::class.java)
        intent.putExtra(KEY_URI_MUSIC, movie)
        startActivity(intent)


    }

    override fun onItemLongClick(position: AudioBean) {
        mCurrentAudio = position
        val optionsDialog = ActionOptionsDialog(
            requireActivity(),
            DESTS,
            ICONS,
            this
        )
        optionsDialog.show()
        optionsDialog.setOnClickListener(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::mPlayServiceConnection.isInitialized) {
            requireContext().unbindService(mPlayServiceConnection)
        }
        mLocalBroadcastManager.unregisterReceiver(myLocalBroadcastReceiver)
    }

    override fun getLayoutId(): Int {

        return R.layout.fragment_movies
    }

    override fun onOption1Click() {
        val intent = Intent(requireActivity(), ConfirmDeleteActivity::class.java)
        intent.putExtra("mCurrentAudio", mCurrentAudio)
        startActivity(intent)
    }

    override fun onOption2Click() {
    }

    override fun onOption3Click() {
    }

    override fun onOption4Click() {
    }

    private inner class MyLocalBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val playService = BaseAppHelper.get().playService
            playService.updatePlayingPosition()
            playService.playPause()
            setupMovieBeanList()
        }
    }

}